/**
 * 初始化页面
 */
$(function () {

    //发异步，从Java获取所有权限数据
    $.ajax({
        type: 'get',
        url: requestURL+prefix+userService+'/permission/pageList',
        headers: {"Authorization": authToken},
        // 权限只获取type=2的 ,2:按钮 真正的权限
        data: {"page":1,"limit":100,"type":2},
        success: function (data) {
            if (data.status == 0 ) {
                // console.log('权限:==' + JSON.stringify(data));
                setData(data);
                return false;
            }
            if (data.status == 403) {
                layui.layer.msg('权限不足，请联系超级管理员！', {icon: 0, time: 1200});
                return false;
            }
            // console.log(data);
            layer.msg('信息获取失败，请稍后重试！', {icon: 0, time: 1200});
            return false;
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            var state = XMLHttpRequest.status;
            if (state == 403) {
                layui.layer.msg('权限不足，请联系超级管理员！', {icon: 0, time: 1200});
                return false;
            }
            layui.layer.msg('请求接口异常！', {icon: 0, time: 1200});
            return false;
        }

    });
});

/**
 * Layui延迟执行操作
 */
function layuiRole() {
    layui.use(['form', 'layer', 'laydate', 'jquery'], function () {
        $ = layui.jquery;
        var form = layui.form,
            laydate = layui.laydate;
        layer = layui.layer;

        // 查询当前角色所拥有的权限
        // 当前角色ID
        var id = sessionStorage.getItem('id');
        // console.log(id);
        //发异步，从Java获取数据
        $.ajax({
            type: 'get',
            url: requestURL+prefix+userService+'/role-permission/findByRoleId/' + id,
            headers: {"Authorization": authToken},
            success: function (data) {
                var redFruits = [200,204];
                for (let i = 0; i < redFruits.length; i++) {
                    if (data.status ==  redFruits[i] ) {
                        // console.log("当前角色所属权限ID：" + JSON.stringify(data.object));
                        // 赋值
                        $("#L_id").val(data.object.id);
                        // 当前角色所有权限信息
                        let pids = data.object.pids;
                        // 获取到所有权限信息
                        let res = getData();
                        // 遍历权限信息
                        if (res.total > 0) {
                            let permissionList = res.list;
                            // 将全部权限进行回显
                            for (let j = 0; j < permissionList.length; j++) {
                                let permission = "<input type='checkbox' name='permission' value='" + permissionList[j].id + "' title='" + permissionList[j].name + "' />\n"
                                $("#permissionIds").append(permission);
                                layui.form.render();
                            }
                        }
                        // 获取到角色所属权限值进行匹配
                        for (let i = 0; i < pids.length; i++) {
                            $("#permissionIds :checkbox").each(function () {
                                if (this.value == pids[i]) {
                                    $(this).prop("checked",true);
                                    layui.form.render();
                                }
                            })
                        }
                        return false;
                    }
                }
                // console.log(data);
                layer.msg('信息获取失败，请稍后重试！', {icon: 0, time: 1200});
                return false;
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {
                var state = XMLHttpRequest.status;
                if (state == 403) {
                    layui.layer.msg('权限不足，请联系超级管理员！', {icon: 0, time: 1200});
                    return false;
                }
                layui.layer.msg('请求接口异常！', {icon: 0, time: 1200});
                return false;
            }

        });


        //监听提交
        form.on('submit(add)', function (data) {
            // 爱好是否选中
            var arr_box = [];
            $("#permissionIds :checkbox").each(function () {
                var isCheck = $(this).prop("checked");
                if ('checked' == isCheck || isCheck) {
                    arr_box.push(this.value);
                }
            });
            if (arr_box.length == 0) {
                layer.msg('请选择权限哦', {icon: 2, time: 1000});
                return false;
            }
            // 进行引用赋值
            data.field.permissionIds = arr_box.toString();
            // console.log(data.field);
            //发异步，把数据提交给Java
            $.ajax({
                type: 'post',
                url: requestURL+prefix+userService+'/role-permission/save',
                headers: {"Authorization": authToken},
                data: JSON.stringify(data.field),
                contentType: 'application/json;charset=utf-8',
                dataType: 'json',
                success: function (res) {
                    if (res.message == "success") {
                        $("#sumbit").attr("disabled", true); //禁止点击按钮
                        layer.msg('修改成功！', {
                            icon: 1, time: 1100, end: function () {
                                // 可以对父窗口进行刷新
                                xadmin.father_reload();
                            }
                        });
                        return false;
                    }
                    layer.msg('修改失败！', {icon: 2, time: 1200});
                    return false;
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    var state = XMLHttpRequest.status;
                    if (state == 403) {
                        layui.layer.msg('权限不足，请联系超级管理员！', {icon: 0, time: 1200});
                        return false;
                    }
                    layui.layer.msg('请求接口异常！', {icon: 0, time: 1200});
                    return false;
                }

            });
            return false;
        });

    });

}

/**
 * 由于上个请求没完就开始了
 * 200毫秒之后执行Layui操作
 */
setTimeout(function () {
    layuiRole();
}, 300);


/**
 * 将异步获取角色数据进行赋值
 * @param data
 * @returns {*}
 */
let roleData;

function setData(data) {
    roleData = data;
}

/**
 * 获取roleData
 * @returns {*}
 */
function getData() {
    return roleData;
}